package com.seven.restaurant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seven.restaurant.entity.po.FoodPO;
import com.seven.restaurant.entity.request.FoodRequest;
import com.seven.restaurant.entity.request.PageRequset;
import com.seven.restaurant.entity.vo.FoodDetailsVO;
import com.seven.restaurant.mapper.FoodMapper;
import com.seven.restaurant.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author BaiBan
 * @since 2022-07-18
 */
@Service
public class FoodviceImpl extends ServiceImpl<FoodMapper, FoodPO> implements FoodService {

    @Autowired
    FoodMapper mapper;

    @Override
    public IPage<FoodDetailsVO> list(PageRequset pageRequset) {
        Page<FoodDetailsVO> page = new Page<>(pageRequset.getCurrent(), pageRequset.getSize());

        QueryWrapper<FoodPO> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("recommend", "update_time")  // 按照推荐，更新时间降序排列
                .eq("del", 0);
        return mapper.selectDetailsPage(page, wrapper);
    }

    @Override
    public Boolean save(FoodRequest FoodRequest) {
        FoodPO FoodPO = toFoodPO(FoodRequest);
        return mapper.insert(FoodPO) == 1;
    }

    @Override
    public Boolean update(FoodRequest FoodRequest) {
        FoodPO FoodPO = toFoodPO(FoodRequest);
        return mapper.updateById(FoodPO) == 1;
    }

    @Override
    public Boolean update(Long id) {
        FoodPO FoodPO = mapper.selectById(id);
        FoodPO.setRecommend(FoodPO.getRecommend() ^ 1);
        return (mapper.updateById(FoodPO) == 1);
    }

    /**
     * Food类 {@link FoodRequest} 转化成 {@link FoodPO}
     */
    private FoodPO toFoodPO(FoodRequest request) {
        FoodPO po = new FoodPO();
        po.setId(request.getId());
        po.setName(request.getName());
        po.setIcon(request.getIcon());
        po.setType(request.getType());
        po.setBriefIntroduction(request.getBriefIntroduction());
        po.setPrice(request.getPrice());
        return po;
    }
}
